package com.study;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GuestServlet extends HttpServlet {
	private static final long serialVersionUID = -4008561075593299385L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		EntityManagerFactory emf = (EntityManagerFactory)this.getServletContext().getAttribute("emf");
		EntityManager em = emf.createEntityManager();
		
		try {
			String name = req.getParameter("name");
			if(name != null) {
				em.getTransaction().begin();
				em.persist(new Guest(name));
				em.getTransaction().commit();
			}
			
			// display
			List<Guest> guestList = em.createQuery("select t from Guest t", Guest.class).getResultList();
			
			req.setAttribute("guests", guestList);
			req.getRequestDispatcher("/guest.jsp").forward(req, resp);
		} finally {
			if(em.getTransaction().isActive())
				em.getTransaction().rollback();
			em.close();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)	throws ServletException, IOException {
		doGet(req, resp);
	}

}
